package sunyu.service.shiro.config;

import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sunyu.kit.common.LogKit;
import sunyu.kit.redis.RedisKit;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * shiro使用到的redis配置初始化类
 *
 * @author 孙宇
 */
@Component
public class ShiroRedisConfig {

    public static final String shiroRedisName = "shiroRedis";
    private static final Logger logger = LogKit.getLogger();
    @Resource(name = "webSecurityManager")
    private DefaultWebSecurityManager webSecurityManager;
    @Value("${redis.type}")
    private Integer type;//0单机1集群
    @Value("${redis.cluster}")
    private String cluster;
    @Value("${redis.maxTotal}")
    private Integer maxTotal;
    @Value("${redis.maxIdle}")
    private Integer maxIdle;
    @Value("${redis.maxWaitMillis}")
    private Integer maxWaitMillis;
    @Value("${redis.testOnBorrow}")
    private Boolean testOnBorrow;
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;
    @Value("${redis.connectionTimeout}")
    private Integer connectionTimeout;
    @Value("${redis.password}")
    private String password;

    @PostConstruct
    public void init() {
        if (webSecurityManager.getCacheManager().toString().indexOf("ShiroRedisCacheManager") > -1) {
            logger.info("初始化shiro Redis缓存开始");
            logger.info("redis名称：{}", ShiroRedisConfig.shiroRedisName);
            if (type == 0) {//单机
                logger.info("redis类型：单机");
                logger.info("host：{}", host);
                logger.info("port：{}", port);
                logger.info("password：{}", password);
                RedisKit.addJedisPool(ShiroRedisConfig.shiroRedisName, maxTotal, maxIdle, maxWaitMillis, testOnBorrow, connectionTimeout, host, port, password);
            } else if (type == 1) {//集群
                logger.info("redis类型：集群");
                logger.info("cluster：{}", cluster);
                RedisKit.addJedisCluster(ShiroRedisConfig.shiroRedisName, maxTotal, maxIdle, maxWaitMillis, testOnBorrow, cluster);
            }
            logger.info("初始化shiro Redis缓存结束");
        } else {
            logger.info("shiro使用了ehcache缓存");
            logger.info("ehcache名称：shiroEhCacheManager");
        }
    }

}
